<template>
  <div class="search-page">
    <div class="search-container">
      <h1 class="search-title">AI工具搜索</h1>
      <div class="search-box-container">
        <div class="search-box">
          <input 
            v-model="searchQuery" 
            type="text" 
            placeholder="搜索AI工具..."
            class="search-input"
            @keyup.enter="handleSearch"
            @focus="showSuggestions = true"
            @blur="hideSuggestions"
          />
          <button @click="handleSearch" class="search-btn">
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none">
              <path d="M21 21L16.514 16.506L21 21ZM19 10.5C19 15.194 15.194 19 10.5 19C5.806 19 2 15.194 2 10.5C2 5.806 5.806 2 10.5 2C15.194 2 19 5.806 19 10.5Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
            </svg>
          </button>
        </div>
        
        <!-- 搜索建议下拉框 -->
        <div v-if="showSuggestions && suggestions.length > 0" class="suggestions-dropdown">
          <div 
            v-for="suggestion in suggestions" 
            :key="suggestion" 
            class="suggestion-item"
            @mousedown="selectSuggestion(suggestion)"
          >
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" class="suggestion-icon">
              <path d="M21 21L16.514 16.506L21 21ZM19 10.5C19 15.194 15.194 19 10.5 19C5.806 19 2 15.194 2 10.5C2 5.806 5.806 2 10.5 2C15.194 2 19 5.806 19 10.5Z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
            </svg>
            {{ suggestion }}
          </div>
        </div>
      </div>
      
      <div v-if="searchResults.length > 0" class="search-results">
        <h2>搜索结果</h2>
        <div class="results-grid">
          <div v-for="result in searchResults" :key="result.id" class="result-card">
            <div class="result-icon">
              <img :src="result.icon" :alt="result.name" />
            </div>
            <div class="result-content">
              <h3>{{ result.name }}</h3>
              <p>{{ result.description }}</p>
              <div class="result-tags">
                <span v-for="tag in result.tags" :key="tag" class="tag">{{ tag }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <div v-else-if="hasSearched" class="no-results">
        <p>未找到相关结果，请尝试其他关键词</p>
      </div>
      
      <div v-else class="search-home">
        <!-- 工具分类 -->
        <div v-if="categories.length > 0" class="categories-section">
          <h2>工具分类</h2>
          <div class="categories-grid">
            <div 
              v-for="category in categories" 
              :key="category.name" 
              class="category-card"
              @click="searchByCategory(category.name)"
            >
              <div class="category-name">{{ category.name }}</div>
              <div class="category-count">{{ category.count }} 个工具</div>
            </div>
          </div>
        </div>

        <!-- 热门工具 -->
        <div v-if="popularTools.length > 0" class="popular-tools-section">
          <h2>热门工具</h2>
          <div class="tools-grid">
            <div 
              v-for="tool in popularTools" 
              :key="tool.id" 
              class="tool-card"
              @click="handleToolClick(tool)"
            >
              <div class="tool-icon">
                <img :src="tool.icon" :alt="tool.name" />
              </div>
              <div class="tool-content">
                <h3>{{ tool.name }}</h3>
                <p>{{ tool.description }}</p>
                <div class="tool-meta">
                  <span class="tool-category">{{ tool.category }}</span>
                  <span class="tool-rating">⭐ {{ tool.rating }}</span>
                  <span class="tool-popularity">🔥 {{ tool.popularity }}</span>
                </div>
                <div class="tool-tags">
                  <span v-for="tag in tool.tags" :key="tag" class="tag">{{ tag }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 热门搜索 -->
        <div class="hot-keywords-section">
          <h2>热门搜索</h2>
          
          <!-- 调试信息 -->
          <!-- <div v-if="true" style="background: #333; color: #fff; padding: 10px; margin: 10px 0; border-radius: 5px; font-family: monospace; font-size: 12px;">
            <div>调试信息：</div>
            <div>hotKeywords数组长度: {{ hotKeywords?.length || 0 }}</div>
            <div>hotKeywords内容: {{ JSON.stringify(hotKeywords, null, 2) }}</div>
            <div>searchStore.hotKeywords: {{ JSON.stringify(searchStore.hotKeywords, null, 2) }}</div>
          </div> -->
          
          <div class="suggestions">
            <!-- 无数据提示 -->
            <div v-if="!hotKeywords || hotKeywords.length === 0" class="no-keywords">
              <p>暂无热门关键词</p>
            </div>
            
            <!-- 热门关键词列表 -->
            <span 
              v-else
              v-for="keyword in hotKeywords" 
              :key="keyword" 
              class="suggestion-tag" 
              @click="searchQuery = keyword; handleSearch()"
            >
              {{ keyword }}
            </span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue';
import { useSearchStore } from '../stores/search';

// 初始化store
const searchStore = useSearchStore();
    const searchQuery = ref('');
    const selectedCategory = ref('all');
    const sortBy = ref('relevance');
    const suggestions = ref([]);
    const showSuggestions = ref(false);
    const categories = ref([]);
    const popularTools = ref([]);
    const hasSearched = ref(false);

// 从store获取数据
const searchResults = computed(() => searchStore.searchResults);
const isSearching = computed(() => searchStore.loading);
const searchHistory = computed(() => searchStore.searchHistory);
const hotKeywords = computed(() => searchStore.hotKeywords);

// 移除硬编码的分类数组，使用响应式的 categories ref

const sortOptions = [
  { value: 'relevance', label: '相关度' },
  { value: 'date', label: '时间' },
  { value: 'popularity', label: '热度' }
];

// 过滤和排序搜索结果
const filteredResults = computed(() => {
  let results = searchResults.value;
  
  // 按分类过滤
  if (selectedCategory.value !== 'all') {
    results = results.filter(item => item.type === selectedCategory.value);
  }
  
  return results;
});

const handleSearch = async () => {
  if (!searchQuery.value.trim()) {
    searchStore.clearResults();
    hasSearched.value = false;
    return;
  }
  
  try {
    hasSearched.value = true;
    showSuggestions.value = false;
    
    // 设置过滤器
    searchStore.setFilters({
      category: selectedCategory.value !== 'all' ? selectedCategory.value : '',
      sortBy: sortBy.value
    });
    
    // 执行搜索
    await searchStore.search(searchQuery.value.trim());
  } catch (error) {
    console.error('搜索失败:', error);
  }
};

const performSearch = handleSearch; // 兼容旧方法名

const clearSearch = () => {
  searchQuery.value = '';
  searchStore.clearResults();
  suggestions.value = [];
  showSuggestions.value = false;
  hasSearched.value = false;
};

// 按分类搜索
const searchByCategory = async (categoryName, query = null) => {
  if (query) {
    // 如果提供了查询参数，执行分类搜索
    try {
      let results;
      switch (categoryName) {
        case 'work':
          results = await searchStore.searchWorks(query);
          break;
        case 'contest':
          results = await searchStore.searchContests(query);
          break;
        case 'user':
          results = await searchStore.searchUsers(query);
          break;
        default:
          results = await searchStore.search(query);
      }
      return results;
    } catch (error) {
      console.error('分类搜索失败:', error);
      throw error;
    }
  } else {
    // 如果没有查询参数，设置分类并执行搜索
    selectedCategory.value = categoryName;
    searchQuery.value = categoryName;
    await handleSearch();
  }
};

// 处理工具点击
const handleToolClick = async (tool) => {
  try {
    // 确保ID是数字类型
    const toolId = parseInt(tool.id);
    if (!isNaN(toolId)) {
      // 记录点击
      await searchStore.recordToolClick(toolId);
    }
    
    // 打开工具链接
    if (tool.url) {
      window.open(tool.url, '_blank');
    }
  } catch (error) {
    console.error('处理工具点击失败:', error);
    // 即使记录失败也要打开链接
    if (tool.url) {
      window.open(tool.url, '_blank');
    }
  }
};

// 加载分类数据
const loadCategories = async () => {
  try {
    const result = await searchStore.fetchCategories();
    console.log('加载的分类数据:', result, 333333333);
    categories.value = result || [];
    console.log('加载的分类数据:', categories.value);
  } catch (error) {
    console.error('加载分类失败:', error);
    // 提供默认分类数据
    categories.value = [
      { name: '对话', count: 15 },
      { name: '图像', count: 12 },
      { name: '写作', count: 8 },
      { name: '编程', count: 6 },
      { name: '音频', count: 4 }
    ];
  }
};

// 加载热门工具
const loadPopularTools = async () => {
  try {
    const result = await searchStore.fetchPopularTools(8); // 显示8个热门工具
    popularTools.value = result || [];
    console.log('加载的热门工具数据:', popularTools.value);
  } catch (error) {
    console.error('加载热门工具失败:', error);
    // 提供默认热门工具数据
    popularTools.value = [
      {
        id: 1,
        name: 'ChatGPT',
        description: '强大的AI对话助手，能够回答问题、协助写作、编程等',
        icon: '/img/thumb.jpg',
        category: '对话',
        rating: 4.8,
        popularity: 95,
        tags: ['对话', 'AI助手', '写作'],
        url: 'https://chat.openai.com'
      },
      {
        id: 2,
        name: 'Midjourney',
        description: 'AI图像生成工具，创造令人惊叹的艺术作品',
        icon: '/img/thumb.jpg',
        category: '图像',
        rating: 4.7,
        popularity: 88,
        tags: ['图像生成', 'AI艺术', '创意'],
        url: 'https://midjourney.com'
      }
    ];
  }
};

// 加载热门关键词
const loadHotKeywords = async () => {
  try {
    await searchStore.fetchHotKeywords(10);
    console.log('加载的热门关键词:', searchStore.hotKeywords);
  } catch (error) {
    console.error('加载热门关键词失败:', error);
  }
};



const getSuggestions = async () => {
  if (!searchQuery.value.trim()) {
    suggestions.value = [];
    showSuggestions.value = false;
    return;
  }
  
  try {
    suggestions.value = await searchStore.getSuggestions(searchQuery.value.trim());
    showSuggestions.value = suggestions.value.length > 0;
  } catch (error) {
    console.error('获取搜索建议失败:', error);
    suggestions.value = [];
    showSuggestions.value = false;
  }
};

const selectSuggestion = (suggestion) => {
  searchQuery.value = suggestion;
  showSuggestions.value = false;
  handleSearch();
};

// 隐藏搜索建议（延迟执行以允许点击）
const hideSuggestions = () => {
  setTimeout(() => {
    showSuggestions.value = false;
  }, 200);
};

const selectHistoryItem = (historyItem) => {
  searchQuery.value = historyItem;
  performSearch();
};

const selectHotKeyword = (keyword) => {
  searchQuery.value = keyword;
  performSearch();
};

const removeFromHistory = (item) => {
  searchStore.removeFromHistory(item);
};

const clearHistory = () => {
  searchStore.clearHistory();
};

const viewItem = (item) => {
  console.log('查看详情:', item);
  // 根据类型导航到相应页面
  switch (item.type) {
    case 'work':
      // 导航到作品详情页
      break;
    case 'contest':
      // 导航到竞赛详情页
      break;
    case 'user':
      // 导航到用户主页
      break;
  }
};

const getItemIcon = (type) => {
  switch (type) {
    case 'work': return '🎨';
    case 'contest': return '🏆';
    case 'user': return '👤';
    default: return '📄';
  }
};

const getItemTypeText = (type) => {
  switch (type) {
    case 'work': return '作品';
    case 'contest': return '竞赛';
    case 'user': return '用户';
    default: return '其他';
  }
};

const loadMore = async () => {
  if (!searchStore.hasMore || isSearching.value) {
    return;
  }
  
  try {
    await searchStore.loadMore(searchQuery.value.trim());
  } catch (error) {
    console.error('加载更多失败:', error);
  }
};

// 监听搜索查询变化，获取搜索建议
watch(searchQuery, (newQuery) => {
  if (newQuery.trim()) {
    // 防抖处理
    clearTimeout(getSuggestions.timer);
    getSuggestions.timer = setTimeout(getSuggestions, 300);
  } else {
    suggestions.value = [];
    showSuggestions.value = false;
  }
});

// 监听分类和排序变化，重新搜索
watch([selectedCategory, sortBy], () => {
  if (searchQuery.value.trim()) {
    performSearch();
  }
});

onMounted(async () => {
  // 初始化搜索历史
  searchStore.initializeHistory();
  
  // 并行加载所有初始数据
  await Promise.all([
    loadCategories(),
    loadPopularTools(),
    loadHotKeywords()
  ]);
});


</script>

<style scoped>
.search-page {
  min-height: 80vh;
  padding: 40px 20px;
}

.search-container {
  max-width: 800px;
  margin: 0 auto;
}

.search-title {
  text-align: center;
  font-size: 2.5rem;
  margin-bottom: 40px;
  background: linear-gradient(45deg, #00d4ff, #ff6b6b);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

/* 搜索框容器 */
.search-box-container {
  position: relative;
  margin-bottom: 40px;
}

.search-box {
  display: flex;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 25px;
  padding: 8px;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

/* 搜索建议下拉框 */
.suggestions-dropdown {
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  background: rgba(30, 30, 30, 0.95);
  border-radius: 15px;
  margin-top: 8px;
  backdrop-filter: blur(20px);
  border: 1px solid rgba(255, 255, 255, 0.1);
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
  z-index: 1000;
  max-height: 300px;
  overflow-y: auto;
}

.suggestion-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px 20px;
  color: rgba(255, 255, 255, 0.8);
  cursor: pointer;
  transition: all 0.2s ease;
  border-bottom: 1px solid rgba(255, 255, 255, 0.05);
}

.suggestion-item:last-child {
  border-bottom: none;
}

.suggestion-item:hover {
  background: rgba(0, 212, 255, 0.1);
  color: #00d4ff;
}

.suggestion-icon {
  opacity: 0.6;
  flex-shrink: 0;
}

.search-input {
  flex: 1;
  background: none;
  border: none;
  padding: 15px 20px;
  color: white;
  font-size: 16px;
  outline: none;
}

.search-input::placeholder {
  color: rgba(255, 255, 255, 0.6);
}

.search-btn {
  background: linear-gradient(45deg, #00d4ff, #ff6b6b);
  border: none;
  border-radius: 20px;
  padding: 12px 20px;
  color: white;
  cursor: pointer;
  transition: all 0.3s ease;
}

.search-btn:hover {
  transform: scale(1.05);
  box-shadow: 0 5px 15px rgba(0, 212, 255, 0.3);
}

.search-results h2,
.search-suggestions h2 {
  margin-bottom: 20px;
  color: rgba(255, 255, 255, 0.9);
}

.results-grid {
  display: grid;
  gap: 20px;
}

.result-card {
  background: rgba(255, 255, 255, 0.1);
  border-radius: 15px;
  padding: 20px;
  display: flex;
  gap: 15px;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.1);
  transition: all 0.3s ease;
}

.result-card:hover {
  background: rgba(255, 255, 255, 0.15);
  transform: translateY(-2px);
}

.result-icon img {
  width: 60px;
  height: 60px;
  border-radius: 12px;
}

.result-content {
  flex: 1;
}

.result-content h3 {
  margin-bottom: 8px;
  color: white;
}

.result-content p {
  color: rgba(255, 255, 255, 0.7);
  margin-bottom: 12px;
  line-height: 1.5;
}

.result-tags {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.tag {
  background: rgba(0, 212, 255, 0.2);
  color: #00d4ff;
  padding: 4px 12px;
  border-radius: 12px;
  font-size: 12px;
  border: 1px solid rgba(0, 212, 255, 0.3);
}

.no-results {
  text-align: center;
  padding: 60px 20px;
  color: rgba(255, 255, 255, 0.6);
}

.suggestions {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
}

.suggestion-tag {
  background: rgba(255, 255, 255, 0.1);
  color: rgba(255, 255, 255, 0.8);
  padding: 8px 16px;
  border-radius: 20px;
  cursor: pointer;
  transition: all 0.3s ease;
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.suggestion-tag:hover {
  background: rgba(255, 255, 255, 0.2);
  color: white;
  transform: translateY(-2px);
}

/* 工具分类样式 */
.categories-section {
  margin-bottom: 40px;
}

.categories-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
  margin-top: 20px;
}

.category-card {
  background: rgba(255, 255, 255, 0.1);
  border-radius: 12px;
  padding: 20px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s ease;
  border: 1px solid rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
}

.category-card:hover {
  background: rgba(255, 255, 255, 0.15);
  transform: translateY(-4px);
  box-shadow: 0 8px 25px rgba(0, 212, 255, 0.2);
}

.category-name {
  font-size: 18px;
  font-weight: 600;
  color: white;
  margin-bottom: 8px;
}

.category-count {
  font-size: 14px;
  color: rgba(255, 255, 255, 0.7);
}

/* 热门工具样式 */
.popular-tools-section {
  margin-bottom: 40px;
}

.tools-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
  margin-top: 20px;
}

.tool-card {
  background: rgba(255, 255, 255, 0.1);
  border-radius: 15px;
  padding: 20px;
  display: flex;
  gap: 15px;
  cursor: pointer;
  transition: all 0.3s ease;
  border: 1px solid rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
}

.tool-card:hover {
  background: rgba(255, 255, 255, 0.15);
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(0, 212, 255, 0.2);
}

.tool-icon {
  flex-shrink: 0;
}

.tool-icon img {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  object-fit: cover;
}

.tool-content {
  flex: 1;
  min-width: 0;
}

.tool-content h3 {
  margin: 0 0 8px 0;
  color: white;
  font-size: 16px;
  font-weight: 600;
}

.tool-content p {
  margin: 0 0 12px 0;
  color: rgba(255, 255, 255, 0.7);
  font-size: 14px;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.tool-meta {
  display: flex;
  gap: 12px;
  margin-bottom: 8px;
  flex-wrap: wrap;
}

.tool-category,
.tool-rating,
.tool-popularity {
  font-size: 12px;
  padding: 2px 8px;
  border-radius: 8px;
  background: rgba(0, 212, 255, 0.2);
  color: #00d4ff;
  border: 1px solid rgba(0, 212, 255, 0.3);
}

.tool-tags {
  display: flex;
  gap: 6px;
  flex-wrap: wrap;
}

.tool-tags .tag {
  font-size: 11px;
  padding: 2px 6px;
}

/* 热门搜索样式 */
.hot-keywords-section {
  margin-bottom: 40px;
}

.hot-keywords-section h2 {
  margin-bottom: 20px;
  color: rgba(255, 255, 255, 0.9);
}

.no-keywords {
  text-align: center;
  padding: 20px;
  color: rgba(255, 255, 255, 0.6);
  font-style: italic;
}

.no-keywords p {
  margin: 0;
  font-size: 14px;
}

/* 搜索首页布局 */
.search-home {
  max-width: 1200px;
  margin: 0 auto;
}

.search-home h2 {
  font-size: 1.5rem;
  margin-bottom: 20px;
  color: rgba(255, 255, 255, 0.9);
  font-weight: 600;
}

@media (max-width: 768px) {
  .search-title {
    font-size: 2rem;
  }
  
  .search-box {
    flex-direction: column;
    gap: 10px;
  }
  
  .result-card {
    flex-direction: column;
    text-align: center;
  }
  
  .suggestions {
    justify-content: center;
  }
  
  .categories-grid {
    grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
    gap: 12px;
  }
  
  .tools-grid {
    grid-template-columns: 1fr;
  }
  
  .tool-card {
    flex-direction: column;
    text-align: center;
  }
  
  .tool-meta {
    justify-content: center;
  }
}
</style>